package com.bdth.controller;

import com.bdth.model.*;
import com.bdth.service.IDeviceService;
import com.bdth.service.IEnclosureBindService;
import com.bdth.service.IEnclosureService;
import com.bdth.service.ITerminalCommandService;
import com.bdth.utils.HtmlUtil;
import com.bdth.utils.JT808Constants;
import com.bdth.utils.SessionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: 徐斌
 * @Date: 2018-05-03 14:12
 */
@Controller
@RequestMapping("/sendEnclosure")
public class SendEnclosureController extends BaseController {

	protected static final Logger logger = LoggerFactory.getLogger(SendEnclosureController.class);

	@Autowired
	private IEnclosureBindService enclosureBindService;

	@Autowired
	private ITerminalCommandService terminalCommandService;

	@Autowired
	private IEnclosureService enclosureService;

	@Autowired
	private IDeviceService deviceService;

	@RequestMapping("/selectPage")
	public ModelAndView selectPage(String page, int dvcId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> context = getRootMap();
		context.put("dvcId", dvcId);
		return forword("/enclosureBind/" + page, context);
	}

	@RequestMapping("/send")
	public void Send(String areaIds, int dvcId, String bindType, int configType, HttpServletRequest request, HttpServletResponse response) throws Exception {
		int commandId = 0;
		Map<String, Object> context = new HashMap<String, Object>();
		try {
			String[] enclosureId = areaIds.split(",");
			for (String strId : enclosureId) {
				int id = Integer.parseInt(strId);
				EnclosureConfig ec = enclosureService.queryById(id);
				//EnclosureBind eb = getBinding(id, dvcId);
				if (bindType.equals(EnclosureBind.BINDING_TERMINAL)) {
					if (ec != null) {
						TerminalCommandNew tc = createCommandNew(ec, configType, dvcId, request, response);
						//eb.setCommandID(tc.getTerminalCommandID());
						//commandId = tc.getTerminalCommandID();
					}
				}
				/*eb.setConfigType(configType);
				eb.setBindType(bindType);
				if (eb.getId() == null) {
					eb.setCreateDate(new Date());
					enclosureBindService.add(eb);
				} else {
					enclosureBindService.updateBySelective(eb);
				}*/

			}
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}
		context.put(SUCCESS, true);
		//context.put("data", commandId);
		HtmlUtil.writerJson(response, context);
	}


	private EnclosureBind getBinding(int enclosureId, int dvcId) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("enclosureId", enclosureId);
		map.put("dvcId", dvcId);
		EnclosureBind eb = new EnclosureBind();
		List<EnclosureBind> ebList = enclosureBindService.queryByMapList(map);
		if (ebList == null || ebList.size() == 0) {
			eb.setDvcId(dvcId);
			eb.setEnclosureId(enclosureId);
		} else {
			eb = ebList.get(0);
		}
		return eb;
	}

	private TerminalCommandNew createCommandNew(EnclosureConfig ec, int configType, int dvcId, HttpServletRequest request, HttpServletResponse response) throws Exception {

		TerminalCommandNew tc = new TerminalCommandNew();
		User user = SessionUtils.getUser(request);
		Device device = deviceService.queryById(dvcId);
		tc.setCmdData("" + ec.getId());
		tc.setUserId(user.getLoginName());
		tc.setOwner(TerminalCommandNew.FROM_PLATFORM);
		tc.setRemark("");
		tc.setCmd("" + configType);
		if (device != null) {
			tc.setSimNo(device.getSimNo());
		} else {
			tc.setSimNo("");
		}
		if (EnclosureConfig.CIRCLE.equals(ec.getEnclosureType())) {
			tc.setCmdType(JT808Constants.CMD_CIRCLE_CONFIG);
			if (configType == 3) {
				tc.setCmdType(JT808Constants.CMD_DELETE_CIRCLE);
			}
		} else if (EnclosureConfig.RECT.equals(ec.getEnclosureType())) {
			tc.setCmdType(JT808Constants.CMD_RECT_CONFIG);
			if (configType == 3) {
				tc.setCmdType(JT808Constants.CMD_DELETE_RECT);
			}
		} else if (EnclosureConfig.POLYGON.equals(ec.getEnclosureType())) {
			tc.setCmdType(JT808Constants.CMD_POLYGON_CONFIG);
			if (configType == 3) {
				tc.setCmdType(JT808Constants.CMD_DELETE_POLYGON);
			}
		}

		terminalCommandService.sendCallTerminal(tc);
		return tc;

	}


	private TerminalCommand createCommand(EnclosureConfig ec, int configType, int dvcId, HttpServletRequest request, HttpServletResponse response) throws Exception {

		TerminalCommand tc = new TerminalCommand();
		tc.setCmdContent("" + ec.getId());
		tc.setCmdType("" + configType);
		tc.setCreateDate(new Date());
		tc.setCmdSource(TerminalCommand.FromPlatform);
		tc.setState(TerminalCommand.STATUS_NEW);
		if (EnclosureConfig.CIRCLE.equals(ec.getEnclosureType())) {
			tc.setCmdType("" + JT808Constants.CMD_CIRCLE_CONFIG);
			if (configType == 3) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_CIRCLE);
			}
		} else if (EnclosureConfig.RECT.equals(ec.getEnclosureType())) {
			tc.setCmdType("" + JT808Constants.CMD_RECT_CONFIG);
			if (configType == 3) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_RECT);
			}
		} else if (EnclosureConfig.POLYGON.equals(ec.getEnclosureType())) {
			tc.setCmdType("" + JT808Constants.CMD_POLYGON_CONFIG);
			if (configType == 3) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_POLYGON);
			}
		}

		SendCommand(tc, dvcId, request, response);
		return tc;

	}


	protected void SendCommand(TerminalCommand tc, int dvcId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Device device = deviceService.queryById(dvcId);
		if (device != null) {
			tc.setSimNo(device.getSimNo());
		}
		User user = SessionUtils.getUser(request);
		if (user != null) {
			tc.setUserID(user.getId());
		}
		terminalCommandService.sendTerminalCommand(tc);

	}


	/**
	 * 删除终端的某一区域类型的所有区域
	 *
	 * @return
	 */
	public void deleteAll(int dvcId, String enclosureType, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> context = new HashMap<String, Object>();
		int commandId = 0;
		try {

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdContent("");
			if (EnclosureConfig.CIRCLE.equals(enclosureType)) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_CIRCLE);
			} else if (EnclosureConfig.RECT.equals(enclosureType)) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_RECT);
			} else if (EnclosureConfig.POLYGON.equals(enclosureType)) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_POLYGON);
			} else if (EnclosureConfig.ROUTE.equals(enclosureType)) {
				tc.setCmdType("" + JT808Constants.CMD_DELETE_ROUTE);
			}

			SendCommand(tc, dvcId, request, response);
			commandId = tc.getId();
			List<EnclosureBind> ebList = getAllBinding(dvcId,
					enclosureType);
			for (EnclosureBind eb : ebList) {
				eb.setCommandID(tc.getId());
				eb.setConfigType(3);
			}
			enclosureBindService.updateBatch(ebList);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		context.put(SUCCESS, true);
		context.put("data", commandId);
		HtmlUtil.writerJson(response, context);
	}


	private List<EnclosureBind> getAllBinding(int dvcId, String enclosureType) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("bindType", EnclosureBind.BINDING_TERMINAL);
		Device device = deviceService.queryById(dvcId);
		if (device != null) {
			map.put("simNo", device.getSimNo());
		} else {
			map.put("simNo", "");
		}
		List<EnclosureBind> ebList = enclosureBindService.queryByMapList(map);
		List<EnclosureBind> result = new ArrayList<EnclosureBind>();
		for (EnclosureBind eb : ebList) {
			EnclosureConfig ec = enclosureService.queryById(eb.getEnclosureId());
			if (ec != null) {
				if (ec.getEnclosureType().equals(enclosureType)) {
					result.add(eb);
				}
			}
		}
		return result;
	}


	@RequestMapping("/dataList")
	public void dataList(PageModel pageModel, int dvcId, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		User user = SessionUtils.getUser(request);

		if (user == null) {
			String path = request.getContextPath();
			response.sendRedirect(path + "/login");
		}

		String name = request.getParameter("name");
		String enclosureType = request.getParameter("enclosureType");
		String bindState = request.getParameter("bindState");
		Device device = deviceService.queryById(dvcId);
		if (device != null) {
			map.put("simNo", device.getSimNo());
		} else {
			map.put("simNo", "");
		}
		map.put("userName", user.getLoginName());
		map.put("name", name);
		map.put("enclosureType", enclosureType);
		map.put("bindState", bindState);

		List<Integer> depIds = getDepIds(user.getDepId());
		map.put("depIds", depIds);

		//紧跟着的第一个查询方法会被分页
		PageHelper.startPage(pageModel.getPage(), pageModel.getRows());
		List<Map> dataList = enclosureBindService.queryBindEnclosures(map);

		for (Map map1 : dataList) {
			String value = TerminalCommand.TCommandStatus.get("" + map1.get("commandStatus"));
			map1.put("commandStatus", value);
		}

		//获得结果集条总数
		PageInfo pageList = new PageInfo(dataList);
		//设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", pageList.getTotal());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}

}
